package com.nari.ncps.screen.service.impl.electric;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperFuelFromMapper;
import com.nari.ncps.screen.service.electric.ElectricProdoperFuelFromService;
import com.nari.ncps.screen.vo.electric.CoalSourceDistribution;
import com.nari.ncps.screen.entity.electric.ElectricProdoperFuelFrom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 燃料来源表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperFuelFromServiceImpl extends ServiceImpl<ElectricProdoperFuelFromMapper, ElectricProdoperFuelFrom> implements ElectricProdoperFuelFromService {

    @Autowired
    private ElectricProdoperFuelFromMapper electricProdoperFuelFromMapper;

    /**
     * 煤炭来源分布情况
     * @param year
     * @return
     */
    @Override
    public List<ElectricProdoperFuelFrom> distributionCoalSources(Integer year) {
        LambdaQueryWrapper<ElectricProdoperFuelFrom> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperFuelFrom::getYear, year);
        return this.list(lqw);
    }

    /**
     * 获取每个电厂的煤炭来源分布情况
     * @param year 年份（可选，默认当前年）
     * @return 煤炭来源分布列表
     */
    @Override
    public List<CoalSourceDistribution> getCoalSourceDistributionByPlant(Integer year) {
        // 如果year为空，设置为当前年
        if (year == null) {
            year = DateUtil.year(new Date());
        }
        // 南矿 、北矿 、扎矿、二号矿 、三号矿
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();

        // 构建查询条件
        LambdaQueryWrapper<ElectricProdoperFuelFrom> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperFuelFrom::getYear, currentYear)
                .isNotNull(ElectricProdoperFuelFrom::getCoalSourceAmount)
                .orderByAsc(ElectricProdoperFuelFrom::getOrgCode);

        // 执行查询
        List<ElectricProdoperFuelFrom> entityList = electricProdoperFuelFromMapper.selectList(lqw);

        // 按org_code分组
        Map<String, List<ElectricProdoperFuelFrom>> groupedByOrgCode = entityList.stream()
                .collect(Collectors.groupingBy(ElectricProdoperFuelFrom::getOrgCode));

        List<CoalSourceDistribution> resultList = new ArrayList<>();

        // 处理每个电厂单位的数据
        for (Map.Entry<String, List<ElectricProdoperFuelFrom>> entry : groupedByOrgCode.entrySet()) {
            String orgCode = entry.getKey();
            List<ElectricProdoperFuelFrom> orgDataList = entry.getValue();

            // 获取电厂名称（取第一条记录的电厂名称）
            String orgName = orgDataList.get(0).getOrgName();

            // 初始化各矿类型的煤炭量
            BigDecimal southMineAmount = BigDecimal.ZERO;  // 0-南矿
            BigDecimal northMineAmount = BigDecimal.ZERO;  // 1-北矿
            BigDecimal zaMineAmount = BigDecimal.ZERO;     // 2-扎矿
            BigDecimal no2MineAmount = BigDecimal.ZERO;    // 3-二号矿
            BigDecimal no3MineAmount = BigDecimal.ZERO;    // 4-三号矿

            // 遍历该电厂的所有记录，按煤炭来源类型分类汇总
            for (ElectricProdoperFuelFrom entity : orgDataList) {
                BigDecimal amount = entity.getCoalSourceAmount();
                if (amount == null) continue;

                // 转换为万吨（除以10000）
                BigDecimal amountInTenThousand = amount.divide(BigDecimal.valueOf(10000), 6, BigDecimal.ROUND_HALF_UP);

                Integer coalMineType = entity.getCoalMineType();
                if (coalMineType != null) {
                    switch (coalMineType) {
                        case 0: // 南矿
                            southMineAmount = southMineAmount.add(amountInTenThousand);
                            break;
                        case 1: // 北矿
                            northMineAmount = northMineAmount.add(amountInTenThousand);
                            break;
                        case 2: // 扎矿
                            zaMineAmount = zaMineAmount.add(amountInTenThousand);
                            break;
                        case 3: // 二号矿
                            no2MineAmount = no2MineAmount.add(amountInTenThousand);
                            break;
                        case 4: // 三号矿
                            no3MineAmount = no3MineAmount.add(amountInTenThousand);
                            break;
                    }
                }
            }

            // 创建CoalSourceDistribution对象
            CoalSourceDistribution distribution = new CoalSourceDistribution();
            distribution.setYear(currentYear);
            distribution.setMonth(null); // 数据中没有月份信息
            distribution.setPowerPlantCode(orgCode);
            distribution.setPowerPlantName(orgName);
            distribution.setSouthMineAmount(southMineAmount.compareTo(BigDecimal.ZERO) > 0 ? southMineAmount : null);
            distribution.setNorthMineAmount(northMineAmount.compareTo(BigDecimal.ZERO) > 0 ? northMineAmount : null);
            distribution.setZaMineAmount(zaMineAmount.compareTo(BigDecimal.ZERO) > 0 ? zaMineAmount : null);
            distribution.setNo2MineAmount(no2MineAmount.compareTo(BigDecimal.ZERO) > 0 ? no2MineAmount : null);
            distribution.setNo3MineAmount(no3MineAmount.compareTo(BigDecimal.ZERO) > 0 ? no3MineAmount : null);

            resultList.add(distribution);
        }

        return resultList;


//
//        // 查询原始数据
//        List<ElectricProdoperFuelFrom> rawDataList = this.distributionCoalSources(year);
//
//        // 按电厂分组数据
//        List<CoalSourceDistribution> result = new ArrayList<>();
//
//        // 获取所有不同的电厂编码
//        List<String> powerPlantCodes = rawDataList.stream()
//                .map(ElectricProdoperFuelFrom::getOrgCode)
//                .distinct()
//                .collect(Collectors.toList());
//
//        // 为每个电厂构建CoalSourceDistribution对象
//        for (String powerPlantCode : powerPlantCodes) {
//            CoalSourceDistribution distribution = new CoalSourceDistribution();
//            distribution.setYear(year);
//
//            // 获取该电厂的所有数据
//            List<ElectricProdoperFuelFrom> plantDataList = rawDataList.stream()
//                    .filter(data -> powerPlantCode.equals(data.getOrgCode()))
//                    .collect(Collectors.toList());
//
//            // 设置电厂名称（从任意一条记录中获取）
//            if (!plantDataList.isEmpty()) {
//                distribution.setPowerPlantCode(powerPlantCode);
//                distribution.setPowerPlantName(plantDataList.get(0).getOrgName());
//            }
//
//            // 根据coalMineType设置不同的煤矿来源量
//            for (ElectricProdoperFuelFrom fuelFrom : plantDataList) {
//                Byte coalMineType = fuelFrom.getCoalMineType();
//                switch (coalMineType) {
//                    case 0: // 南矿
//                        distribution.setSouthMineAmount(fuelFrom.getCoalSourceAmount());
//                        break;
//                    case 1: // 北矿
//                        distribution.setNorthMineAmount(fuelFrom.getCoalSourceAmount());
//                        break;
//                    case 2: // 扎矿
//                        distribution.setZaMineAmount(fuelFrom.getCoalSourceAmount());
//                        break;
//                    case 3: // 二号矿
//                        distribution.setNo2MineAmount(fuelFrom.getCoalSourceAmount());
//                        break;
//                    case 4: // 三号矿
//                        distribution.setNo3MineAmount(fuelFrom.getCoalSourceAmount());
//                        break;
//                }
//            }
//
//            result.add(distribution);
//        }
//

//        return result;
    }
}